package org.budo.support.slf4j.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.budo.support.lang.counter.Counter;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public class Slf4jUtil {
    private static final Map<String, Long> _MAP_1 = new ConcurrentHashMap<String, Long>();

    private static final String INFO = "info";

    private static final String WARN = "warn";

    public static void warn(Logger logger, Integer period, String format, Object... arguments) {
        logAfterCount(logger, WARN, period, format, arguments);
    }

    /**
     * @param logger
     * @param period
     * @param format    应该不变,会以此为单位
     * @param arguments
     */
    public static void info(Logger logger, Integer period, String format, Object... arguments) {
        logAfterCount(logger, INFO, period, format, arguments);
    }

    private static void logAfterCount(Logger logger, String level, Integer period, String format, Object... arguments) {
        String key = logger + ":" + level + ":" + format;

        Long value = _MAP_1.get(key);
        Long _now = System.currentTimeMillis();

        // 计数
        Counter counter = Counter.of(key);
        counter.increment();

        if (null == value || value + period < _now) {
            doLog(logger, level, format, counter, arguments);
            counter.setValue(0);

            _MAP_1.put(key, _now);
            return;
        }

        // 还在周期内,不打
    }

    private static void doLog(Logger logger, String level, String format, Counter counter, Object... arguments) {
        if (INFO.equalsIgnoreCase(level)) {
            logger.info("#57 count : " + counter.getValue() + ", " + format, arguments);
            return;
        }

        if (WARN.equalsIgnoreCase(level)) {
            logger.warn("#61 count : " + counter.getValue() + ", " + format, arguments);
            return;
        }

        logger.error("#66 count : " + counter.getValue() + ", " + format, arguments);
    }
}